package com.soloyogame.anitoys.my.web.controller.front.orders;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.text.DecimalFormat;import java.text.Format;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.TreeMap;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import net.sf.json.JSONArray;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.mvc.support.RedirectAttributes;import com.alibaba.fastjson.JSON;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.soloyogame.anitoys.db.bean.OrderCustInputInfo;import com.soloyogame.anitoys.db.bean.Spec;import com.soloyogame.anitoys.db.commond.Account;import com.soloyogame.anitoys.db.commond.AccountCoupon;import com.soloyogame.anitoys.db.commond.AccountDeductibleVoucher;import com.soloyogame.anitoys.db.commond.AccountFinance;import com.soloyogame.anitoys.db.commond.AccountPointsLog;import com.soloyogame.anitoys.db.commond.AccountRankLog;import com.soloyogame.anitoys.db.commond.Address;import com.soloyogame.anitoys.db.commond.Area;import com.soloyogame.anitoys.db.commond.Business;import com.soloyogame.anitoys.db.commond.BusinessShipping;import com.soloyogame.anitoys.db.commond.BusinessShippingDetail;import com.soloyogame.anitoys.db.commond.CartInfo;import com.soloyogame.anitoys.db.commond.Comment;import com.soloyogame.anitoys.db.commond.Express;import com.soloyogame.anitoys.db.commond.Order;import com.soloyogame.anitoys.db.commond.Orderdetail;import com.soloyogame.anitoys.db.commond.Orderlog;import com.soloyogame.anitoys.db.commond.Orderpay;import com.soloyogame.anitoys.db.commond.Ordership;import com.soloyogame.anitoys.db.commond.PayInfo;import com.soloyogame.anitoys.db.commond.Product;import com.soloyogame.anitoys.db.commond.ProductStock;import com.soloyogame.anitoys.db.commond.SystemSetting;import com.soloyogame.anitoys.db.page.PagerModel;import com.soloyogame.anitoys.my.web.controller.front.FrontBaseController;import com.soloyogame.anitoys.my.web.controller.front.util.LoginUserHolder;import com.soloyogame.anitoys.my.web.controller.front.util.RequestHolder;import com.soloyogame.anitoys.service.AccountCouponService;import com.soloyogame.anitoys.service.AccountDeductibleVoucherService;import com.soloyogame.anitoys.service.AccountFinanceService;import com.soloyogame.anitoys.service.AddressService;import com.soloyogame.anitoys.service.AreaService;import com.soloyogame.anitoys.service.BusinessService;import com.soloyogame.anitoys.service.ExpressService;import com.soloyogame.anitoys.service.OrderBusinessShippingService;import com.soloyogame.anitoys.service.OrderService;import com.soloyogame.anitoys.service.OrderdetailService;import com.soloyogame.anitoys.service.OrderlogService;import com.soloyogame.anitoys.service.OrderpayService;import com.soloyogame.anitoys.service.OrdershipService;import com.soloyogame.anitoys.service.PointsManageService;import com.soloyogame.anitoys.service.ProductService;import com.soloyogame.anitoys.service.SpecService;import com.soloyogame.anitoys.service.SystemSettingService;import com.soloyogame.anitoys.util.JsonUtil;import com.soloyogame.anitoys.util.KeyTool;import com.soloyogame.anitoys.util.PropertiesUtil;import com.soloyogame.anitoys.util.apiStore.ApiStore;import com.soloyogame.anitoys.util.apiStore.ApiStoreInfo;import com.soloyogame.anitoys.util.apiStore.ApiStoreItem;import com.soloyogame.anitoys.util.cache.RedisCacheProvider;import com.soloyogame.anitoys.util.cache.RedisClient;import com.soloyogame.anitoys.util.constants.ManageContainer;/** * 门户订单服务类 * @author shaojian */@Controller("frontOrderAction")@RequestMapping("order")public class OrderAction extends FrontBaseController<Order> {	private static final Logger logger = LoggerFactory.getLogger(OrderAction.class);	private static final long serialVersionUID = 1L;	@Autowired	private OrderService orderService;	@Autowired	private OrderdetailService orderdetailService;	@Autowired	private OrderpayService orderpayService;	@Autowired	private ProductService productService;	@Autowired	private OrdershipService ordershipService;	@Autowired	private AddressService addressService;	@Autowired	private RedisCacheProvider redisCacheProvider;	@Autowired	private OrderBusinessShippingService orderBusinessShippingService;	@Autowired	private AccountFinanceService accountFinanceService;	@Autowired	private AccountCouponService accountCouponService;	@Autowired	private SpecService specService;	@Autowired	private OrderlogService orderlogService;	@Autowired	private BusinessService businessService;	@Autowired	private ExpressService expressService;	@Autowired    private SystemSettingService systemSettingService;	//@TODO	@Autowired	private SystemSetting systemSetting;	@Autowired    PointsManageService pointsManageService;	@Autowired	private AccountDeductibleVoucherService accountDeductibleVoucherService;	private String url;	@Autowired	private RedisClient redisClient;        public String getUrl() {		return url;	}	public void setUrl(String url) {		this.url = url;	}	  /**     * 区域服务接口     */    @Autowired    private AreaService areaService;    // 收货地址数量限制    private static final int addressCount = 20;	@Override	public OrderService getService() 	{		return orderService;	}	public void setOrderService(OrderService orderService) 	{		this.orderService = orderService;	}	/**	 * 订单确认页面，点击这个页面的确认支付按钮则会跳转到支付宝等的支付页面	 * 	 * @return	 */	@RequestMapping("orderConfirm")	public String orderConfirm() 	{		logger.info("into method orderConfirm");		return "order/confirmOrder";	}		/**	 * 从商品详情页面进入订单确认页面	 * @param model	 * @param request	 * @return	 * @author zhangjing	 */	@RequestMapping(value="toPlacPayFromDetail", method = RequestMethod.POST)	public String toPlacPayFromDetail(ModelMap model, HttpServletRequest request) 	{		//获得登陆用户信息，若获取空，则跳转登陆页面		Account account = getLoginAccount();		if (account == null || StringUtils.isBlank(account.getAccount())) 		{			return page_toLoginRedirect;		}		//获取前台传递商品id		String productID = request.getParameter("productId");            //商品ID		logger.info("productID = " + productID);		//获取前台传递购买数量		int buyCount = Integer.valueOf(request.getParameter("buyCount"));//购买数量		//获取前台传递选中的规格id		String buySpecID = request.getParameter("buySpecID");            //选中的规格ID		//若获取商品id为空或购买数量小于0，则抛出异常（“商品id传递失败！”）		if(StringUtils.isEmpty(productID) || buyCount < 0) 		{			throw new IllegalArgumentException("商品id传递失败！");		}		//根据商品id查询获取产品信息		Product product = productService.selectById(productID);		logger.info("现货/预售商品标识（1-现货，2-预售）：" + product.getProductType());		//将客户购买数量赋值		product.setBuyCount(buyCount);		/*		 * 加载指定商品的规格信息		 */		if(StringUtils.isNotBlank(buySpecID)) 		{			//根据选中的规格id查询获取规格信息			Spec spec = specService.selectById(buySpecID);			if(spec == null) 			{				throw new NullPointerException("根据指定的规格"+buySpecID+"查询不到任何数据!");			}			//将匹配的规格信息赋值			product.setBuySpecInfo(spec);			//减少以后的逻辑判断，规格的价格等同于商品的价格			product.setNowPrice(spec.getSpecPrice());		}		//根据用户id获取用户配送地址列表		Address address = new Address();		address.setAccountId(account.getId());		List<Address> addressList =  addressService.selectList(address);		logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");		//将用户配送地址list传递前台		model.addAttribute("addressList", addressList);		model.addAttribute("addressListSize", addressList.size());		List<Order> sonOrderList = new ArrayList<Order>();	//子订单集合		Order sonOrder = new Order();	//子订单实体		//子订单商品总金额 = 商品购买数量 * 商品现价		sonOrder.setPtotal(Double.toString(product.getBuyCount() * Double.parseDouble(product.getNowPrice())));		//若商品为现货商品 ，标记子订单类型为现货		if(product.getProductType() == Order.PROD_TYPE_XIAN) 		{			sonOrder.setOrderType(Order.PROD_TYPE_XIAN); //现货			sonOrder.setRemark("现货商品订单");			//子订单总金额，此处暂时将商品总金额赋值，后会根据优惠、抵扣、运费等金额更新			sonOrder.setAmount(Double.toString(product.getBuyCount() * 					Double.parseDouble(product.getNowPrice())));//子订单总金额 -- 定金（子订单商品购买数量 * 商品现价）		} 		//若商品为预售商品，标记子订单类型为预售		else if(product.getProductType() == Order.PROD_TYPE_YUSHOU) 		{			sonOrder.setOrderType(Order.PROD_TYPE_YUSHOU); //预售			sonOrder.setRemark("预售商品订单");			//子订单总金额，此处暂时将商品总金额赋值，后会根据优惠、抵扣、运费等金额更新			sonOrder.setAmount(Double.toString(product.getBuyCount() * 					Double.parseDouble(product.getDepositPrice())));//子订单总金额 -- 定金（子订单商品购买数量 * 商品预售价）			sonOrder.setAdvancePrice(Double.toString(product.getBuyCount() * 					Double.parseDouble(product.getDepositPrice())));//首付款 -- 定金（子订单商品购买数量 * 商品预售价）			sonOrder.setBalancePrice(Double.toString(Double.parseDouble(sonOrder.getPtotal()) - 					Double.parseDouble(sonOrder.getAdvancePrice())));//补款余额 -- 预售商品总价 - 首付款		}		//创建订单号		String orderCode = KeyTool.creatKey();		sonOrder.setOrderCode(orderCode);		sonOrder.setOrderCodeView(orderCode.substring(8));		/*		 * 根据客户购买商品创建订单详情信息		 * 并赋值到子订单orderDetailList属性中		 * 因此方法是从商品详细页面进入，故一个子订单对应的是一个子订单详情		 */		List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();		Orderdetail orderdetail = createOrderDetail(product);		orderDetailList.add(orderdetail);		sonOrder.setOrderdetail(orderDetailList);				sonOrder.setQuantity(product.getBuyCount());		sonOrder.setAccount(account.getId());		//子订单所获积分 = 商品积分 * 购买数量		sonOrder.setScore(product.getScore() * product.getBuyCount());		sonOrder.setBusinessId(product.getBusinessId());		if(StringUtils.isNotBlank(product.getBusinessId())) 		{			//根据商品商家编号查询获取商家信息			Business business = businessService.selectById(product.getBusinessId());			sonOrder.setBusinessName(business.getBusinessName());		//子订单商家名称		}		//根据商家id获取配送方式list		List<BusinessShipping> businessShippingList = 				orderBusinessShippingService.queryOrderBusinessShipping(product.getBusinessId());		sonOrder.setBusinessShippingList(businessShippingList);		/*		 * 根据用户id和商家id获取用户有效优惠券list		 * 创建一个优惠券实体，表示用户不使用优惠券，并添加到list第一位，用于前台默认展示		 * 并将优惠券list赋值到子订单中		 */		List<AccountCoupon> accountCouponList = 				accountCouponService.selectAccountCouponList(account.getId(), product.getBusinessId());		AccountCoupon accountCoupon = new AccountCoupon();		accountCoupon.setId("MF0001");		accountCoupon.setCouponName("未使用优惠券");		accountCoupon.setCouponValue("0.0");		accountCouponList.add(0, accountCoupon);		sonOrder.setAccountCouponList(accountCouponList);		//用于区分预售/现货商品子订单	0 -- 预售 1 -- 现货		sonOrder.setOrderFlag(0);		sonOrderList.add(sonOrder);		//将子订单list传递前台		model.addAttribute("sonOrderList", sonOrderList);		//根据用户信息和子订单list创建父订单信息		Order parentOrder = createParentOrder(account, sonOrderList);		/*		 * 根据用户id获取用户平台抵扣券list		 * 创建一个抵扣券实体，表示用户不使用抵扣券，并添加到list第一位，用于前台默认展示		 * 并将抵扣券list赋值到父订单中		 */		List<AccountCoupon> accountVoucherList = 				accountCouponService.selectAccountVoucherList(account.getId());		AccountCoupon accountVoucher = new AccountCoupon();		accountVoucher.setId("MFPT0001");		accountVoucher.setCouponName("未使用抵扣券");		accountVoucher.setCouponValue("0.0");		accountVoucherList.add(0, accountVoucher);		parentOrder.setAccountVoucherList(accountVoucherList);		//将父订单传递到前台		model.addAttribute("parentOrder", parentOrder);		//根据用户id获取用户积分信息		int rank = 0;		AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());		if(accountFinance != null) 		{			rank = accountFinance.getRank();		}		//将用户积分传递前台		model.addAttribute("rank", rank);		//将父订单存入redis中，做后面逻辑使用		redisCacheProvider.put(account.getId() + "parentOrder", parentOrder);		//跳转到订单确认页面		return "order/plac";	}		/**	 * 购物车进入订单确认页面，点击页面的去结算按钮进入订单确认页面	 * @param model	 * @param ids	购物车中用户勾选的付款商品id	 * @return	跳转订单确认页面	 * @author zhangjing	 */	@RequestMapping("plac")	public String placPay(ModelMap model, String[] ids) 	{		//获得用户信息		Account account = getLoginAccount();		//若获取登录用户信息为null，则跳到登陆页面		if (account == null || StringUtils.isBlank(account.getAccount())) 		{			return page_toLoginRedirect;		}		//根据登陆用户id获取用户地址列表		Address address = new Address();		address.setAccountId(account.getId());		List<Address> addressList =  addressService.selectList(address);		logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");		//将用户地址list传递前台		model.addAttribute("addressList", addressList);		//获取用户选中的商品信列表（这里暂时生成一个临时的子订单，不进行插库）		List<Order> sonOrderList = this.createSonOrderInfo(account, ids);				logger.info("子订单个数：" + sonOrderList.size());		//将临时子订单传递前台		model.addAttribute("sonOrderList", sonOrderList);		//根据子订单生成临时父订单		Order parentOrder = this.createParentOrder(account, sonOrderList);		//根据用户id获取用户平台抵扣券list		List<AccountCoupon> accountVoucherList = accountCouponService.selectAccountVoucherList(account.getId());		//生成一个默认的抵扣券，表示用户未使用任何抵扣券		AccountCoupon accountCoupon = new AccountCoupon();		accountCoupon.setId("MFPT0001");		accountCoupon.setCouponName("未使用抵扣券");		accountCoupon.setCouponValue("0.0");		accountVoucherList.add(0, accountCoupon);		parentOrder.setAccountVoucherList(accountVoucherList);		//将父订单传递前台		model.addAttribute("parentOrder", parentOrder);		//将父订单信息存入radis缓存中，供后流程使用，注意绑定用户id//		if(redisCacheProvider.get(account.getId() + "parentOrder") != null) {//			redisCacheProvider.remove(account.getId() + "parentOrder");//		}		redisCacheProvider.put(account.getId() + "parentOrder", parentOrder);		//根据用户id获取用户积分信息		int rank = 0;		AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());		if(accountFinance != null) 		{			rank = accountFinance.getRank();		}		//将用户积分信息传递前台		model.addAttribute("rank", rank);		//跳转到订单确认页面		return "order/plac";	}		/**	 * 生成子订单集合	 * @param account	登陆用户信息	 * @param ids	购物车中用户勾选的付款商品id	 * @return List<Order> 子订单集合	 * @author zhangjing	 */	private List<Order> createSonOrderInfo(Account account, String[] ids) 	{		List<Order> sonOrderList = new ArrayList<Order>();		//子订单集合，既返回结果集		List<Product> productList = new ArrayList<Product>();		//用于存放购物车用户选中商品列表		//从redis中获取用户购物车中所有商品列表		CartInfo cartInfo = (CartInfo) redisCacheProvider.get("user_"+account.getId()+"Cart");				if(cartInfo == null || cartInfo.getProductList().size() == 0) 		{			throw new NullPointerException("用户购物车中没有可支付的商品!");		}		//若用户有选中商品付款，则将勾选商品放入productList，供后使用		if(ids != null && ids.length > 0) 		{			for(int i = 0; i < ids.length; i++) 			{				for(Iterator<Product> it = cartInfo.getProductList().iterator(); it.hasNext();) 				{					Product p = it.next();					if(p.getId().equals(ids[i])) 					{						productList.add(p);						break;					}				}			}		}		//创建用于存放用户选择付款现货商品集合		List<Product> productXianList = new ArrayList<Product>();				for(Product product : productList) 		{			//logger.info("product.getBuySpecInfo().getId() = " + product.getBuySpecInfo().getId());			logger.info("商品（" + product.getId() + "）标识（1-现货，2-预售）：" + product.getProductType() +					"\n" + "商家id = " + product.getBusinessId());			//若商品为现货			if(product.getProductType() == Order.PROD_TYPE_XIAN) 			{				productXianList.add(product);			} 			//若为预售商品			else if(product.getProductType() == Order.PROD_TYPE_YUSHOU) 			{				//随机生成子订单号				String orderCode = KeyTool.creatKey();				//创建子订单实体				Order sonOrder = new Order();					sonOrder.setOrderCode(orderCode);						//子订单号				sonOrder.setOrderCodeView(orderCode.substring(8));		//预防过长，只截取8位				sonOrder.setNumber(product.getBuyCount());				//子订单商品购买数量				sonOrder.setPtotal(Double.toString(product.getBuyCount() * 						Double.parseDouble(product.getNowPrice())));	//子订单商品总价（子订单商品购买数量 * 商品现价）				sonOrder.setQuantity(product.getBuyCount());			//子订单商品总数量				sonOrder.setAmount(Double.toString(product.getBuyCount() * 						Double.parseDouble(product.getDepositPrice())));//子订单总金额 -- 定金（子订单商品购买数量 * 商品预售价）				sonOrder.setAdvancePrice(Double.toString(product.getBuyCount() * 						Double.parseDouble(product.getDepositPrice())));//首付款 -- 定金（子订单商品购买数量 * 商品预售价）				sonOrder.setBalancePrice(Double.toString(Double.parseDouble(sonOrder.getPtotal()) - 						Double.parseDouble(sonOrder.getAdvancePrice())));//补款余额 -- 预售商品总价 - 首付款				sonOrder.setOrderType(Order.PROD_TYPE_YUSHOU); 			//子订单类型				sonOrder.setAccount(account.getId());					//子订单用户id				sonOrder.setScore(product.getScore());					//子订单获赠的积分				sonOrder.setBusinessId(product.getBusinessId());		//子订单商家编号				if(!StringUtils.isBlank(product.getBusinessId())) 				{					//根据商品商家编号查询获取商家信息					Business business = businessService.selectById(product.getBusinessId());					sonOrder.setBusinessName(business.getBusinessName());//子订单商家名称				}				sonOrder.setIsSaleorder(0);								//是否售后订单				//根据商品商家编号获取商家配送方式list				List<BusinessShipping> businessShippingList = orderBusinessShippingService.queryOrderBusinessShipping(product.getBusinessId());				sonOrder.setBusinessShippingList(businessShippingList);	//子订单配送方式地址				//根据用户id和商家编号获取该用户在该商家的优惠券list				List<AccountCoupon> accountCouponList = accountCouponService.selectAccountCouponList(account.getId(), product.getBusinessId());				//生成一个默认的优惠券，表示用户未使用任何优惠券				AccountCoupon accountCoupon = new AccountCoupon();				accountCoupon.setId("MF0001");				accountCoupon.setCouponName("未使用优惠券");				accountCoupon.setCouponValue("0.0");				accountCouponList.add(0, accountCoupon);				sonOrder.setAccountCouponList(accountCouponList);		//子订单商家优惠券				sonOrder.setOrderFlag(0);								//用于区分预售/现货商品子订单 0 -- 预售 1-- 现货				sonOrder.setLowStocks("y");								//子订单库存状态				sonOrder.setRemark("预售商品订单");							//子订单备注				//子订单详情列表				List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();				Orderdetail orderdetail = this.createOrderDetail(product);				orderDetailList.add(orderdetail);				sonOrder.setOrderdetail(orderDetailList);				sonOrder.setStatus(Order.order_status_init);			//子订单状态				sonOrderList.add(sonOrder);			}		}		//针对所有现货生成子订单 -- 同一个仓库的现售商品生成同一个子订单		if(productXianList.size() >= 1) 		{			while(true) 			{				List<Product> productSamBusiness = new ArrayList<Product>();		//用于存放同一商家的商品				//随机生成订单号				String orderCode = KeyTool.creatKey();								Product productXian = productXianList.get(productXianList.size() - 1);								List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();				Orderdetail orderdetail = this.createOrderDetail(productXian);				orderDetailList.add(orderdetail);								productSamBusiness.add(productXian);				productXianList.remove(productXianList.size() - 1);				int quantity = productXian.getBuyCount();		//商品个数				double ptotal = productXian.getBuyCount() * Double.parseDouble(productXian.getNowPrice());					int score = productXian.getScore();				for(int i = productXianList.size() - 1; i >= 0; i--) 				{					if(productXian.getBusinessId().equals(productXianList.get(i).getBusinessId())) 					{						quantity += productXianList.get(i).getBuyCount();						ptotal += productXianList.get(i).getBuyCount() * Double.parseDouble(productXianList.get(i).getNowPrice());						score += productXianList.get(i).getScore();												Orderdetail orderdetailSam = this.createOrderDetail(productXianList.get(i));						orderdetailSam.setOrderID(orderCode);						orderDetailList.add(orderdetailSam);						productSamBusiness.add(productXianList.get(i));						productXianList.remove(i);					}				}				logger.info("商品个数：" + quantity + "，结算商品总金额：" + ptotal);				Order sonOrder = new Order();	//子订单实体				sonOrder.setOrderCode(orderCode);				sonOrder.setOrderCodeView(orderCode.substring(8));				sonOrder.setPtotal(Double.toString(ptotal));				sonOrder.setQuantity(quantity);				sonOrder.setAmount(sonOrder.getPtotal());				sonOrder.setOrderType(Order.PROD_TYPE_XIAN); //现售				sonOrder.setAccount(account.getId());				sonOrder.setScore(score);				sonOrder.setRemark("现售商品订单");				sonOrder.setBusinessId(productXian.getBusinessId());				if(!StringUtils.isBlank(productXian.getBusinessId())) 				{					Business business = businessService.selectById(productXian.getBusinessId());					sonOrder.setBusinessName(business.getBusinessName());				}				sonOrder.setBusinessShippingList(orderBusinessShippingService.queryOrderBusinessShipping(productXian.getBusinessId()));				//优惠券				List<AccountCoupon> accountCouponList= accountCouponService.selectAccountCouponList(account.getId(), productXian.getBusinessId());				//logger.info("优惠券类型：" + accountCouponList.get(0).getCouponType());				AccountCoupon accountCoupon = new AccountCoupon();				accountCoupon.setId("MF0001");				accountCoupon.setCouponName("未使用优惠券");				accountCoupon.setCouponValue("0.0");				accountCouponList.add(0, accountCoupon);				sonOrder.setAccountCouponList(accountCouponList);				sonOrder.setOrderFlag(1);				sonOrder.setOrderdetail(orderDetailList);				sonOrder.setStatus(Order.order_status_init);				sonOrderList.add(sonOrder);				//为了退出无限循环				if(productXianList.size() == 0) 				{					break;				}			}		}		return sonOrderList;	}		/**	 * 创建父订单信息	 * @param account			//登陆用户信息	 * @param sonOrderList		//子订单列表	 * @return	 * @author zhangjing	 */	private Order createParentOrder(Account account, List<Order> sonOrderList) 	{		//创建大订单对象		Order pareOrder = new Order();		pareOrder.setOrders(sonOrderList);		pareOrder.setAccount(account.getId());		//随机生成订单号		String orderCode = KeyTool.creatKey();		pareOrder.setOrderCode(orderCode);		pareOrder.setOrderCodeView(orderCode.substring(8));		//计算商品总数量		int quantity = 0;		int score = 0;		double ptotal = 0;		//子订单商品总金额		double amount = 0;		//子订单总金额（区别预售）		for(Order sonOrder : sonOrderList) 		{			quantity += sonOrder.getQuantity();			score += sonOrder.getScore();			ptotal += Double.parseDouble(sonOrder.getPtotal());			amount += Double.parseDouble(sonOrder.getAmount());		}		pareOrder.setQuantity(quantity);		pareOrder.setScore(score);		pareOrder.setPtotal(Double.toString(ptotal));         //订单商品总金额		pareOrder.setStatus(Order.order_status_init);		pareOrder.setPaystatus(Order.order_paystatus_n);		//订单总金额 = 内存订单总金额 (初始默认大订单总金额 = 子订单商品总金额)		pareOrder.setAmount(Double.toString(amount));		if(sonOrderList.size() == 1) 		{			pareOrder.setRemark("1笔订单");		} 		else 		{			pareOrder.setRemark("合并|" + sonOrderList.size()+"笔订单");		}        /*		 * 对金额进行格式化，防止出现double型数字计算造成的益出。		 */		DecimalFormat df = new DecimalFormat("0.00");		pareOrder.setAmount(df.format(Double.valueOf(pareOrder.getAmount())));//订单总金额		pareOrder.setPtotal(df.format(Double.valueOf(pareOrder.getPtotal())));//订单商品总金额		//pareOrder.setFee(df.format(Double.valueOf(pareOrder.getFee())));//订单总配送费		return pareOrder;	}	/**	 * 创建订单明细信息	 * @param product	 * @return	 * @author zhangjing	 */	private Orderdetail createOrderDetail(Product product) 	{		logger.info("**** " + product.getId() + " || " + product.getProductWeight());		Orderdetail orderdetail = new Orderdetail();		orderdetail.setProductID(Integer.parseInt(product.getId()));		orderdetail.setProductName(product.getName());		orderdetail.setPrice(product.getNowPrice());		orderdetail.setNumber(product.getBuyCount());		orderdetail.setTotal0(Double.toString(Double.parseDouble(product.getNowPrice()) * product.getBuyCount()));		orderdetail.setSpecId(product.getSpecJsonString());		orderdetail.setSpecInfo(product.getIntroduce());		orderdetail.setGoodsStatus(product.getStatus());		orderdetail.setGoodsImg(product.getImages());		orderdetail.setFirstType(product.getFirstType());		orderdetail.setSecontType(product.getSecondType());		orderdetail.setDepositPrice(product.getDepositPrice());		orderdetail.setBalancePrice(product.getBalancePrice());		orderdetail.setGiftID(product.getGiftID());		//orderdetail.setScore(product.getScore());//活的赠送的积分		orderdetail.setPicture(product.getPicture());		orderdetail.setProductWeight(product.getProductWeight());		if(product.getBuySpecInfo() != null) 		{			//按照规格计算			orderdetail.setSpecInfo("规格一:"+product.getBuySpecInfo().getSpecSize()+"，规格二:"+product.getBuySpecInfo().getSpecColor());			orderdetail.setSpecId(product.getBuySpecInfo().getId());			orderdetail.setSpecSize(product.getBuySpecInfo().getSpecSize());			orderdetail.setSpecColor(product.getBuySpecInfo().getSpecColor());		}		return orderdetail;	}		/**	 * 跳转立即支付页面	 * @param model	 * @return	 * @throws Exception	 * @author zhangjing	 */	@RequestMapping(value = "pay")	public void pay(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception	{		logger.info("pay method start");		String intoType = request.getParameter("intoType");		String accountVoucher = request.getParameter("accountVoucher");		String parentAmount = request.getParameter("parentAmount");		String addressId = request.getParameter("addressId");		String point = request.getParameter("point");		String usedScore = request.getParameter("usedScore");		logger.info("accountVoucher = " + accountVoucher + ",parentAmount = " + parentAmount + 				",addressId = " + addressId + ",point = " + point + ",usedScore = " + usedScore);		Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息		//购物车进入支付		if("placPay".equals(intoType)) 		{			List<OrderCustInputInfo> list = new ArrayList<OrderCustInputInfo>();			String orderCust = request.getParameter("orderCust");			if(!orderCust.isEmpty())			{			 	JSONArray jsonArray = new JSONArray().fromObject(orderCust);				list = (List)JSONArray.toCollection(jsonArray, OrderCustInputInfo.class);			}			//获得大订单信息			Order parentOrder = (Order)redisCacheProvider.get(account.getId() + "parentOrder");			parentOrder.setSelectAddressID(addressId);			Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");			parentOrder.setCreatedate(format.format(new Date()));			parentOrder.setAddTime(new Date());			parentOrder.setAmount(parentAmount);			if(!StringUtils.isBlank(usedScore)) 			{				parentOrder.setIsUsePoint(1);				parentOrder.setAmountExchangeScore(Integer.parseInt(usedScore));			} 			else 			{				parentOrder.setIsUsePoint(0);				parentOrder.setAmountExchangeScore(0);			}			if(!StringUtils.isBlank(accountVoucher)) 			{				parentOrder.setDeductibleId(accountVoucher.split(",")[0]);				parentOrder.setDeductible(accountVoucher.split(",")[1]);			}						List<Order> sonOrderList = parentOrder.getOrders();	//子订单信息			for(Order sonOrder : sonOrderList) 			{				for(OrderCustInputInfo orderCustInputInfo : list) 				{					logger.info(orderCustInputInfo.toString());					if(sonOrder.getOrderCode().equals(orderCustInputInfo.getOrderCode())) 					{						sonOrder.setCarry(orderCustInputInfo.getExpressCode());     //运送方式 						sonOrder.setExpressCode(orderCustInputInfo.getExpressCode());						sonOrder.setExpressName(orderCustInputInfo.getExpressName());						sonOrder.setFee(orderCustInputInfo.getFee());						sonOrder.setOtherRequirement(orderCustInputInfo.getOtherRequirement());						//sonOrder.setPtotal(orderCustInputInfo.getPtotal());						sonOrder.setAmount(orderCustInputInfo.getPtotal());						//sonOrder.setAdvancePrice(orderCustInputInfo.getPtotal());						sonOrder.setIsSaleorder(0);						if(null != orderCustInputInfo.getCouponsId() && !"".equals(orderCustInputInfo.getCouponsId())) 						{							sonOrder.setCouponsId(orderCustInputInfo.getCouponsId().split(",")[0]);							sonOrder.setCoupons(orderCustInputInfo.getCouponsId().split(",")[1]);							sonOrder.setIsUserCoupons(1);						} 						else 						{							sonOrder.setIsUserCoupons(0);						}						sonOrder.setRefundStatus("0");      //退款状态  0-未退款 1--退款					}				}			}			 insertAndPay(parentOrder, model, response,parentAmount);		} 		//待补款进入支付		else if("placAdd".equals(intoType)) 		{			Order addOrder = (Order) redisCacheProvider.get(account.getId() + "addOrder");			addOrder.setSelectAddressID(addressId);			if(StringUtils.isNotBlank(accountVoucher)) 			{				addOrder.setDeductibleId(accountVoucher.split(",")[0]);				addOrder.setDeductible(accountVoucher.split(",")[1]);			}						addOrder.setCarry(request.getParameter("expressCode"));     //运送方式 			addOrder.setExpressCode(request.getParameter("expressCode"));			addOrder.setExpressName(request.getParameter("expressName"));			addOrder.setFee(request.getParameter("fee"));			addOrder.setOtherRequirement(request.getParameter("otherRequirement"));			addOrder.setPtotal(request.getParameter("ptotal"));			addOrder.setIsSaleorder(0);			if(request.getParameter("couponsId")!=null) 			{				addOrder.setCouponsId(request.getParameter("couponsId"));				addOrder.setCoupons(request.getParameter("couponValue"));				addOrder.setIsUserCoupons(1);				 if(addOrder.getFee()!=null){					 addOrder.setAmount(String.valueOf(Double.valueOf(addOrder.getAmount())+Double.valueOf(addOrder.getFee())-Double.valueOf(addOrder.getCoupons())));                   } 			} 			else 			{				addOrder.setIsUserCoupons(0);				if(StringUtils.isNotBlank(addOrder.getFee())){					addOrder.setAmount(String.valueOf(Double.valueOf(addOrder.getAmount())+Double.valueOf(addOrder.getFee())));                } 			}			addOrder.setRefundStatus("0");      //退款状态  0-未退款 1--退款			if(!StringUtils.isBlank(usedScore)) 			{				addOrder.setIsUsePoint(1);				addOrder.setAmountExchangeScore(Integer.parseInt(usedScore));			} 			else 			{				addOrder.setIsUsePoint(0);				addOrder.setAmountExchangeScore(0);			}			if(!StringUtils.isBlank(accountVoucher)) 			{				addOrder.setDeductibleId(accountVoucher.split(",")[0]);				addOrder.setDeductible(accountVoucher.split(",")[1]);			}			//更新订单信息			orderService.update(addOrder);			if(!StringUtils.isBlank(usedScore)) 			{				addOrder.setIsUsePoint(1);				DecimalFormat df   = new DecimalFormat("######0.00");   				addOrder.setAmount(df.format((Double.valueOf(addOrder.getAmount())*100-Double.valueOf(usedScore))/100));			} 			redisCacheProvider.put(account.getId() + "mainOrder", addOrder);			//添加配送信息			Ordership ordership = orderService.createOrdershipInfo(addOrder);			ordership.setOrderid(String.valueOf(addOrder.getId()));			ordershipService.update(ordership);		}	}		/**     * 创建订单，并跳转到支付页面让用户进行支付     * @param parentOrder     * @param model     * @param response     * @param parentAmount 订单实际支付的金额     * @throws Exception     */    private void insertAndPay(Order parentOrder, ModelMap model, HttpServletResponse response,String parentAmount) throws Exception     {        response.setContentType("application/xml;charset=utf-8");        logger.info("大订单ID：" + parentOrder.getOrderCode());        logger.info("SelectAddressID = " + parentOrder.getSelectAddressID());        //无地址信息，视为非法请求        if (StringUtils.isBlank(parentOrder.getSelectAddressID())) {            throw new NullPointerException("非法请求！");        }                //创建订单并插入到数据库        Order order = orderService.createOrder(parentOrder,parentAmount);		/*		 * 创建订单后，在用户购物车中剔除本次选中商品		 */        CartInfo cartInfo = getMyCart();        List<Order> sonOrderList = parentOrder.getOrders();        //所有子订单        logger.info("包含子订单个数：" + sonOrderList.size());        for (Order sonOrder : sonOrderList)         {            List<Orderdetail> orderdetail = sonOrder.getOrderdetail();            for (int i = 0; i < orderdetail.size(); i++)             {                if (cartInfo != null && cartInfo.getProductList() != null)                {                    for (Iterator<Product> it = cartInfo.getProductList().iterator(); it.hasNext(); )                     {                        Product p = it.next();                        if (p.getId().equals(Integer.toString(orderdetail.get(i).getProductID())))                         {                            it.remove();                            //重新计算总支付金额                            cartInfo.totalCacl();                        }                    }                }            }        }        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息        if (account == null)         {            redisCacheProvider.put("myCart", cartInfo);        }         else         {            redisCacheProvider.put("user_" + account.getId() + "Cart", cartInfo);        }        logger.info("into plac_pay.ftl");        //radis中删除本次下单信息        //redisCacheProvider.remove(account.getId() + "parentOrder");        redisCacheProvider.put(account.getId() + "mainOrder", order);    }		/**	 * 	 * @param model	 * @return	 * @author zhangjing	 */	@RequestMapping(value = "plac_pay", method = RequestMethod.POST)	public String toPlacPay(ModelMap model) 	{		//查询帐户余额		Account account = getLoginAccount();		if (account == null || StringUtils.isBlank(account.getAccount())) 		{			return page_toLoginRedirect;		}		Order mainOrder = (Order) redisCacheProvider.get(account.getId() + "mainOrder");		AccountFinance aFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());		if(aFinance!=null)		{			model.addAttribute("accountAmount", aFinance.getAmount());		}		model.addAttribute("mainOrder", mainOrder);		//redisCacheProvider.remove("mainOrder");		return "order/plac_pay";	}		/**	 * 进入补款订单确认页面	 * @param model	 * @return	 * @author zhangjing	 */	@RequestMapping("plac_add")	public String toAddPay(ModelMap model, @ModelAttribute("order") Order order1) 	{		//获得用户信息		Account account = getLoginAccount();		if (account == null || StringUtils.isBlank(account.getAccount())) 		{			return page_toLoginRedirect;		}		String orderId = RequestHolder.getRequest().getParameter("id");		logger.info("plac_add:orderId = " + orderId);		//根据id查询子订单信息		Order order = orderService.selectById(orderId);		order.setBusinessShippingList(orderBusinessShippingService.queryOrderBusinessShipping(order.getBusinessId()));		//优惠券		List<AccountCoupon> accountCouponList= accountCouponService.selectAccountCouponList(account.getId(), order.getBusinessId());		order.setAccountCouponList(accountCouponList);		order.setOrderCodeView(order.getOrderCode().substring(8));		//补款时，将子订单尾款赋值于订单金额字段		order.setAmount(order.getBalancePrice());		//平台抵扣券		List<AccountCoupon> accountVoucherList = accountCouponService.selectAccountVoucherList(account.getId());		AccountCoupon accountVoucher = new AccountCoupon();		accountVoucher.setId("MFPT0001");		accountVoucher.setCouponName("未使用抵扣券");		accountVoucher.setCouponValue("0");		accountVoucherList.add(0, accountVoucher);		order.setAccountVoucherList(accountVoucherList);		//根据子订单查询订单详情信息		Orderdetail qayOrderDetail = new Orderdetail();		qayOrderDetail.setOrderID(orderId);		Orderdetail orderDetail = orderdetailService.selectOne(qayOrderDetail);		logger.info("orderDetail.getPicture() = " + orderDetail.getPicture());		/*		 * 加载指定商品的规格信息		 */		if(StringUtils.isNotBlank(orderDetail.getSpecId())) 		{			//根据选中的规格id查询获取规格信息			Spec spec = specService.selectById(orderDetail.getSpecId());			if(spec == null) 			{				throw new NullPointerException("根据指定的规格"+orderDetail.getSpecId()+"查询不到任何数据!");			}			//将匹配的规格信息赋值			orderDetail.setSpecSize(spec.getSpecSize());;			orderDetail.setSpecColor(spec.getSpecColor());		}		model.addAttribute("orderDetail", orderDetail);		//用户积分		int rank = 0;		AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());		if(accountFinance != null) 		{			rank = accountFinance.getRank();		}		model.addAttribute("rank", rank);		//地址列表		Address address = new Address();		address.setAccountId(account.getId());		List<Address> addressList =  addressService.selectList(address);		logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");		model.addAttribute("addressList", addressList);		model.addAttribute("order", order);		redisCacheProvider.put(account.getId() + "addOrder", order);		/**         * 省-市-区         */        Map<String, Area> areaMap = loadArea();        List<Area> cities = new ArrayList<Area>();        List<Area> areas = new ArrayList<Area>();        model.addAttribute("provinces", areaMap.values()); //身份        model.addAttribute("cities", cities);//城市        model.addAttribute("areas", areas);//区县		return "order/plac_add";	}		/**     * 加载省市区数据     */    public Map<String, Area> loadArea()     {        logger.error("loadArea...");        Area area = new Area();        List<Area> areas = areaService.selectFrontList(area);        List<Area> rootAreas = Lists.newArrayList();        for (Area a : areas)         {            if ("100000".equals(a.getPcode()))             {                rootAreas.add(a);            }        }        if (rootAreas.size() == 0)         {            return null;        }        for (Area a : rootAreas)        {            this.getAreaByDigui2(a, areas);        }        Map<String, Area> map = new TreeMap<String, Area>();        for (Area a : rootAreas)         {            map.put(a.getCode(), a);        }        return map;    }        /**     * 递归加载省份下的：城市、区域、以后还会有街道的数据     * @param item     * @param areas 所有的地区列表     */    private void getAreaByDigui2(Area item, final List<Area> areas)     {        List<Area> children = Lists.newArrayList();        for (Area a : areas)         {            if (item.getCode().equals(a.getPcode()))             {                children.add(a);            }        }        item.setChildren(children);        if (children.size() == 0)         {            return;        }        for (Area a : children)         {            getAreaByDigui2(a, areas);        }    }        /**     * 根据省份编码获取城市列表     *     * @return     * @throws IOException     */    @RequestMapping("selectCitysByProvinceCode")    @ResponseBody    public String selectCitysByProvinceCode() throws IOException {        logger.error("selectCitysByProvinceCode...");        String provinceCode = RequestHolder.getRequest().getParameter("provinceCode");        logger.error("selectCitysByProvinceCode...provinceCode=" + provinceCode);        if (StringUtils.isBlank(provinceCode)) {            throw new NullPointerException("provinceCode is null");        }        Map<String, Area> areaMap = loadArea();        if (areaMap != null && areaMap.size() > 0) {            Area areaInfo = areaMap.get(provinceCode);            logger.error("areaInfo = " + areaInfo);            if (areaInfo != null && areaInfo.getChildren() != null && areaInfo.getChildren().size() > 0) {                String jsonStr = JSON.toJSONString(areaInfo.getChildren());                logger.error("jsonStr=" + jsonStr);                return (jsonStr);            }        }        return ("{}");    }    /**     * 根据城市编码获取区域列表     *     * @return     * @throws IOException     */    @RequestMapping("selectAreaListByCityCode")    @ResponseBody    public String selectAreaListByCityCode() throws IOException {        logger.error("selectAreaListByCityCode...");        String provinceCode = RequestHolder.getRequest().getParameter("provinceCode");        String cityCode = RequestHolder.getRequest().getParameter("cityCode");        logger.error("selectAreaListByCityCode...provinceCode=" + provinceCode + ",cityCode=" + cityCode);        if (StringUtils.isBlank(provinceCode) || StringUtils.isBlank(cityCode)) {            throw new NullPointerException("provinceCode or cityCode is null");        }        Map<String, Area> areaMap = loadArea();        if (areaMap != null && areaMap.size() > 0) {            Area city = areaMap.get(provinceCode);            logger.error("areaInfo = " + city);            if (city != null && city.getChildren() != null && city.getChildren().size() > 0) {                for (int i = 0; i < city.getChildren().size(); i++) {                    Area item = city.getChildren().get(i);                    if (item.getCode().equals(cityCode)) {                        if (item.getChildren() != null && item.getChildren().size() > 0) {                            String jsonStr = JSON.toJSONString(item.getChildren());                            logger.error("jsonStr=" + jsonStr);                            return (jsonStr);                        }                    }                }            }        }        return ("{}");    }		/**	 * 点击立即支付按钮，执行订单状态信息修改操作	 * @author zhangjing	 */	@RequestMapping("immediatelyPay")	public String immediatelyPay() 	{		logger.info("immediately pay start....");		String orderid = RequestHolder.getRequest().getParameter("orderid");		Account account = getLoginAccount();				Orderlog orderlog = new Orderlog();		orderlog.setOrderid(orderid);//订单ID		orderlog.setAccount(account.getAccount());//操作人账号		orderlog.setContent("支付成功");//日志内容		orderlog.setAccountType(Orderlog.orderlog_accountType_p);		//orderService.updateOrderStatusByConfirm(orderlog);		logger.info("pay success....");		return "order/paySuccess";	}		 /**     * 补款跳转立即支付页面（传过来的肯定是子订单号）     * @param model     * @return 跳转支付成功页面     * @author zhangjing     */    @RequestMapping(value = "toPay")    @ResponseBody    public String toPay(ModelMap model)     {        //获取登录用户信息，若获取null，则跳转登陆页面        Account account = getLoginAccount();        if (account == null)         {            return page_toLogin;        }        //获取前台传递的订单号(子订单号)        String orderCode = RequestHolder.getRequest().getParameter("orderCode");        //获取前台传递的支付宝金额        String payBaoAmount = RequestHolder.getRequest().getParameter("payBaoAmount");        //获取前台传递的使用余额        String payAccountAmount = RequestHolder.getRequest().getParameter("payAccountAmount");		/*		 * 获取前台传递的支付方式		 * amtWay : 账户余额		 * baoWay ： 支付宝		 * allWay ： 账户余额 + 支付宝		 */        String payWay = RequestHolder.getRequest().getParameter("payWay");        logger.info("orderCode = " + orderCode +                ",payBaoAmount = " + payBaoAmount +                ",payAccountAmount = " + payAccountAmount +                ",payWay = " + payWay);        //若获取前台订单号为空，则抛出异常（“订单号获取失败！”）        if (StringUtils.isBlank(orderCode)) {            throw new IllegalArgumentException("订单号获取失败！");        }        //需要先判断下订单是否已经支付过了(如果没有支付，执行支付操作)        boolean orderPayStatus = orderService.payOrderStatus(orderCode);        if(!orderPayStatus)        {        	Order order = new Order();        	Order parentOrder = null;        	List<Order> sonOrderList = new ArrayList<Order>();        	order.setOrderCode(orderCode);        	order = orderService.selectFrontOne(order);        	Order parentOrderParam = new Order();        	parentOrderParam.setId(order.getParentId());        	parentOrder = orderService.selectFrontOne(parentOrderParam);            sonOrderList.add(order);            // 检查余额 积分 优惠券使用情况            parentOrder.setAmountExchangeScore(order.getAmountExchangeScore());            parentOrder.setPayAccountAmount(payAccountAmount);            parentOrder.setPayBaoAmount(payBaoAmount);//            boolean checkResult = checkAmtAndCoupon(sonOrderList, parentOrder, account, payAccountAmount);//            if (!checkResult)//            {//                return "orderErr";//            }            //获取session            HttpSession session = RequestHolder.getRequest().getSession();            session.setAttribute("orderCode", orderCode);            //订单总金额            session.setAttribute("amount", parentOrder.getAmount());            //商品总金额            session.setAttribute("ptotal", parentOrder.getPtotal());            //只有账户余额方式支付            if ("amtWay".equals(payWay)) {                session.setAttribute("payWay", "amtWay");                //扣减客户账户余额,sql里进行的运算 -_-!                accountFinanceService.cutAccountAmount(account.getId(), payAccountAmount);                // 更新支付后的订单信息                orderService.updateInfoAmtWayPay(parentOrder, sonOrderList, payWay);            }//只有支付宝方式支付            else if ("baoWay".equals(payWay)) {                session.setAttribute("payBaoAmount", payBaoAmount);                session.setAttribute("payWay", "baoWay");                //创建支付信息实体，供调用支付接口使用                PayInfo payInfo = createPayInfo(order);                payInfo.setWIDprice(Double.parseDouble(payBaoAmount));        //支付宝支付金额                payInfo.setPayType("2");                                      //当进入这个方法的时候就是补款支付                session.setAttribute("payInfo", JSON.toJSONString(payInfo));                //跳转支付宝支付页面                return "alipayapi";            }//账户余额+支付宝方式支付            else if ("allWay".equals(payWay)) {                //将账户支付余额传递支付成功页面                session.setAttribute("payAccountAmount", payAccountAmount);                session.setAttribute("payWay", "allWay");                //后调用支付宝支付                PayInfo payInfo = createPayInfo(parentOrder);                payInfo.setWIDprice(Double.parseDouble(payBaoAmount));                session.setAttribute("payInfo", JSON.toJSONString(payInfo));                return "alipayapi";            }//支付方式获取失败            else {                throw new IllegalArgumentException("支付方式获取失败！");            }        }        return "paySuccess";    }        private boolean checkAmtAndCoupon(List<Order> sonOrderList, Order parentOrder, Account account, String payAccountAmount)     {        // 获取用户余额积分        AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());        // 判断余额是否超过        //TODO review?        if (payAccountAmount != null)         {            if (Float.valueOf(payAccountAmount) > Float.valueOf(accountFinance.getAmount()))             {                return false;            }        }        // 判断积分是否超出        if (parentOrder.getAmountExchangeScore() > Integer.valueOf(accountFinance.getRank()))         {            return false;        }        // 判断平台折扣券是否使用        if (StringUtils.isNotBlank(parentOrder.getDeductibleId()))         {            AccountDeductibleVoucher accountDeductibleVoucher = new AccountDeductibleVoucher();            accountDeductibleVoucher.setId(parentOrder.getDeductibleId());            accountDeductibleVoucher.setUserId(account.getId());            AccountDeductibleVoucher result = accountDeductibleVoucherService.selectOne(accountDeductibleVoucher);            if (result.getStatus() == 2)             {                return false;            }        }        // 判断商家优惠券是否使用        for (Order sonOrder : sonOrderList)         {            if (StringUtils.isNotBlank(sonOrder.getCouponsId()))             {                AccountCoupon accountCoupon = new AccountCoupon();                accountCoupon.setId(sonOrder.getCouponsId());                accountCoupon.setUserId(account.getId());                AccountCoupon result = accountCouponService.selectOne(accountCoupon);                if (result.getStatus() == 2)                 {                    return false;                }            }        }        return true;    }		/**	 * 点击我的订单页面的未付款的订单进行付款操作,则跳转到付款页面进行付款	 * @return	 */	@RequestMapping("toOrderPay")	public String toOrderPay()	{		if (getLoginAccount() == null) 		{			return page_toLogin;		}		String id = RequestHolder.getRequest().getParameter("id");		if(StringUtils.isBlank(id))		{			throw new NullPointerException();		}		Order queryOrder = new Order();		queryOrder.setId(id);		Order order = orderService.selectOne(queryOrder);		logger.info("orderId="+order.getId());		if(order==null)		{			throw new NullPointerException("根据订单号查询不到订单信息！");		}		boolean ispayCreate = orderpayService.isOrderpayCreate(order.getId());		logger.debug("立即付款torderpay是否已创建："+ispayCreate);		if(!ispayCreate)		{		//创建支付记录对象			Orderpay orderpay = new Orderpay();			orderpay.setOrderid(order.getId());			orderpay.setPaystatus(Orderpay.orderpay_paystatus_n);						orderpay.setPayamount(Double.valueOf(order.getAmount()));			orderpay.setPaymethod(Orderpay.orderpay_paymethod_alipayescow);			int orderpayID = orderpayService.insert(orderpay);			logger.error("orderpayID="+orderpayID);			order.setOrderpayID(String.valueOf(orderpayID));		}		//查询配送地址信息		RequestHolder.getRequest().getSession().setAttribute("payInfo",JSON.toJSONString(createPayInfo(order)));		systemSetting = systemSettingService.selectOne(new SystemSetting());		return "redirect:"+systemSetting.getPay()+"/alipayapi.jsp";	}			/**	 * 用户进行评论提交	 * @return	 * @throws Exception 	 */	@RequestMapping(value = "doRate", method = RequestMethod.POST)	public String doRate() throws Exception	{		Account acc = getLoginAccount();		if (acc == null) 		{			return page_toLogin;		}		logger.error("doRate...");				String orderid = RequestHolder.getRequest().getParameter("orderid").toString();		Order order = orderService.selectById(String.valueOf(orderid));//		if (StringUtils.isNotBlank(order.getClosedComment())//				&& order.getClosedComment().equals(Order.order_closedComment_y)) {//			//订单的点评功能已被关闭。//			throw new RuntimeException(FrontContainer.request_illegal_error);//		}				/*		 * 用户可以对每个订单项对应的商品进行评价		 */		Orderdetail orderdetail = new Orderdetail();		orderdetail.setOrderID(orderid);		List<Orderdetail> list = orderdetailService.selectList(orderdetail);		List<Comment> comments = new LinkedList<Comment>();		for(int i=0;i<list.size();i++)		{			Orderdetail item = list.get(i);			Product product = productService.selectById(String.valueOf(item.getProductID()));			Comment c = new Comment();			//获取页面上填写的评论类容			String content = RequestHolder.getRequest().getParameter("product_"+item.getProductID());			String commentImage = RequestHolder.getRequest().getParameter("commentImage_"+item.getProductID());			if(!StringUtils.isBlank(commentImage))			{				String realPath = RequestHolder.getRequest().getSession().getServletContext().getRealPath("/");				String resourcePath = "attached/image/OrderRepairsImage/";			               			    File dir = new File(realPath + resourcePath);				if(!dir.exists())				{				    dir.mkdirs();			    }										        File f1, f2;		        f1 = new File(commentImage);		        int lastLength = commentImage.lastIndexOf("."); 		        		        Date date = new Date(System.currentTimeMillis()); 		        String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date); 		        int random = (int)(Math.random()*99); 		        String imageName = strDate+random;                          //以系统时间来随机的创建图片文件名 		        		        String fileType = commentImage.substring(lastLength);              //获取上传图片的类型 		        String src2 = "/attached/image/OrderRepairsImage/"+imageName+fileType;		        String src =RequestHolder.getRequest().getRealPath("") +"\\attached\\image\\OrderRepairsImage\\"+imageName+fileType;				f2 = new File(src);			    this.bcopy(f1, f2);			    c.setCommentImage(src2);			}			logger.debug("orderid="+orderid+"，commentImage="+commentImage+"，content="+content);			if(StringUtils.isBlank(content))			{				continue;			}			c.setProductID(String.valueOf(item.getProductID()));			c.setOrderdetailID(item.getId());			c.setOrderID(String.valueOf(orderid));			c.setContent(content);			c.setStatus(Comment.comment_status_y);			c.setNickname(acc.getNickname());			c.setStar(5);			c.setAccount(acc.getAccountId());			c.setBusinessId(product.getBusinessId());			comments.add(c);		}		//commentService.insertList(comments,acc.getAccount());		return ("redirect:rateSuccess");	}	@RequestMapping("rateSuccess")	public String rateSuccess(ModelMap model)	{		Account acc = getLoginAccount();		if (acc == null) 		{			return page_toLogin;		}		logger.error("rateSuccess...");		CartInfo cartInfo = null;		List<Product> productList = new ArrayList<Product>();		if(acc==null)		{			cartInfo = (CartInfo) redisCacheProvider.get("myCart");		}		else		{			cartInfo = (CartInfo) redisCacheProvider.get("user_"+acc.getAccountId()+"Cart");		}		if(cartInfo!=null)		{			productList = cartInfo.getProductList();		} 		else 		{			cartInfo = new CartInfo();		}		int productCount=productService.selectProductCount();		model.addAttribute("cartInfo", cartInfo);		model.addAttribute("productCount", productCount);		model.addAttribute("productList", productList);				return "order/rateSuccess";	}		public void bcopy(File f1, File f2) 	{	    if (f1.exists()) 	    {	    // 判断要拷贝的文件是否存在	     	     copy(f1,f2);//调用copy方法	    System.out.println("上传文件相关的信息：（名字，路径，大小，最后修改的时间是：）");	    getinfo(f1);	    getinfo(f2);	    System.out.println("上传成功后文件相关的信息：（名字，路径，大小，最后修改的时间是：）");	    } 	    else 	    {	    System.out.println("要拷贝的文件不存在!");	   }	  }	    //获取文件的一些信息	  private void getinfo(File f1) 	  {	   // TODO Auto-generated method stub	   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒");	   if (f1.isFile()) 	   {		   //isFile()方法是测试此抽象路径名表示的文件是否是一个标准文件。	    System.out.println("文件名称：" + f1.getName());	    System.out.println("文件路径：" + f1.getAbsolutePath());	    System.out.println("文件大小：" + f1.length()+"字节(byte)");	    System.out.println("最后修改的时间是：" + sdf.format(new Date(f1.lastModified())));	   } 	   else	   {	    System.out.println("上传成功后获取服务器的相关信息：");	    System.out.println("目录名称：" + f1.getName());	    System.out.println("文件路径：" + f1.getAbsolutePath());	    File[] files = f1.listFiles();	    System.out.println("此目录中有" + files.length + "个文件！");	   }	   System.out.println("_______________________________");	  }	  	  void copy(File f1, File f2) {//f1 源文件路径  f2目标路径   最后把f2 insert 到数据库就不写了		   try 		   {		    // 建立相关的字节输入流		    FileInputStream fr = new FileInputStream(f1); // 通过打开一个到实际文件的连接来创建一个		                // FileInputStream，该文件通过文件系统中的路径名		                		    // 创建一个向具有指定名称的文件中写入数据的输出文件流。		    FileOutputStream fw = new FileOutputStream(f2);		    byte buffer[] = new byte[1]; // 声明一个byte型的数组，数组的大小是512个字节		    while (fr.read(buffer) != -1) { // read()从此输入流中读取一个数据字节，只要读取的结果不！=-1就执行while循环中的语句块		     fw.write(buffer); //write(byte[] b)将 b.length 个字节从指定字节数组写入此文件输出流中。		    }		    fw.close();// 关闭此文件输出流并释放与此流有关的所有系统资源。		    fr.close();		    System.out.println("文件" + f1.getName() + "里的内容已拷贝到文件"		      + f2.getName() + "中！");		   } 		   catch (IOException ioe) 		   {		    System.out.println(ioe);		   }		   catch (Exception e) 		   {		    System.out.println(e);		   }		  }		/**	 * 支付成功后进行评价,转到评论页面	 * @return	 * @throws Exception 	 */	@RequestMapping("rate")	public String rate(@ModelAttribute("e")Order e, ModelMap model) throws Exception	{		Account acc = getLoginAccount();		if (acc == null) 		{			return page_toLogin;		}		String productID = RequestHolder.getRequest().getParameter("productID");		String orderid = RequestHolder.getRequest().getParameter("orderid");		if(StringUtils.isBlank(orderid) && StringUtils.isBlank(productID))		{			throw new NullPointerException("参数异常！");		}				/*		 * 用户可以对每个订单项对应的商品进行评价		 */		Orderdetail orderdetail = new Orderdetail();		orderdetail.setOrderID(orderid);//		orderdetail.setIsComment(Orderdetail.orderdetail_isComment_n);		List<Orderdetail> list = orderdetailService.selectList(orderdetail);		List<Orderdetail> list1 = new ArrayList<Orderdetail>();		if(list !=null && list.size()>0)		{			for (Orderdetail orderdetail2 : list) 			{				if(String.valueOf(orderdetail2.getProductID()).toString().equals(productID))				{					list1.add(orderdetail2);				}			}		}		e.setRateOrderdetailList(list1);		e.setId(orderid);		if(e.getRateOrderdetailList()!=null && e.getRateOrderdetailList().size()==0)		{			e.setRateOrderdetailList(null);		}				//加载商品信息//		product = productService.selectById(productID);		//加载以往用户的评价信息		Comment comment = new Comment();		comment.clear();		comment.setAccount(acc.getAccountId());		comment.setProductID(productID);		comment.setOrderID(orderid);		//Comment comment1 = commentService.selectOne(comment);//		if(comment1==null)//		{//			logger.error("还没有评价");//		}//		else//		{//			logger.error("已经评价过了");//			e.setRateOrderdetailList(null);//		}				//加载指定商品的评论列表//		Comment commentParam = new Comment();//		commentParam.setProductID(Integer.valueOf(productID));//		selectCommentList(commentParam);		model.addAttribute("e", e);		CartInfo cartInfo = null;		List<Product> productList = new ArrayList<Product>();		if(acc==null)		{			cartInfo = (CartInfo) redisCacheProvider.get("myCart");		}		else		{			cartInfo = (CartInfo) redisCacheProvider.get("user_"+acc.getAccountId()+"Cart");		}		if(cartInfo!=null)		{			productList = cartInfo.getProductList();		} 		else 		{			cartInfo = new CartInfo();		}		int productCount=productService.selectProductCount();		model.addAttribute("cartInfo", cartInfo);		model.addAttribute("productCount", productCount);		model.addAttribute("productList", productList);				return "order/rate";	}		/**	 * 分页加载评论	 * @return	 * @throws Exception	 *///	private PagerModel selectCommentList(Comment commentParam) throws Exception //	{//		HttpServletRequest request = RequestHolder.getRequest();//		int offset = 0;//		if (request.getParameter("pager.offset") != null) //		{//			offset = Integer//					.parseInt(request.getParameter("pager.offset"));//		}//		if (offset < 0)//			offset = 0;////		Comment comment = new Comment();//		((PagerModel) commentParam).setOffset(offset);//		//PagerModel pager = commentService.selectPageList(commentParam);//		if(pager==null)pager = new PagerModel();//		// 计算总页数//		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)//				/ pager.getPageSize());//		////		selectListAfter();//		pager.setPagerUrl("rate");//		return pager;//	}		DecimalFormat df = new DecimalFormat("0.00");	/**	 * 创建支付宝的付款信息对象	 * @param order	 */	private PayInfo createPayInfo(Order order) 	{		if(order==null)		{			throw new NullPointerException("参数不能为空！请求非法！");		}				PayInfo payInfo = new PayInfo();		systemSetting = systemSettingService.selectOne(new SystemSetting());		String www = systemSetting.getWww();		/**		 * 解决由于本地和线上正式环境提交相同的商户订单号导致支付宝出现TRADE_DATA_MATCH_ERROR错误的问题。		 * 本地提交的商户订单号前缀是test开头，正式环境提交的就是纯粹的支付订单号		 */		if(www.startsWith("http://127.0.0.1") || www.startsWith("http://localhost"))		{			payInfo.setWIDout_trade_no("test"+order.getOrderCode());		}		else		{			payInfo.setWIDout_trade_no(order.getOrderCode());		}		payInfo.setWIDsubject(order.getProductName());				payInfo.setWIDprice(Double.valueOf(order.getAmount()));		payInfo.setWIDbody(order.getRemark());//		payInfo.setShow_url(SystemManager.systemSetting.getWww()+"/product/"+payInfo.getWIDout_trade_no()+".html");		payInfo.setShow_url(systemSetting.getWww()+"/order/orderInfo.html?id="+order.getId());//		payInfo.setWIDreceive_name(ordership.getShipname());//		payInfo.setWIDreceive_address(ordership.getShipaddress());//		payInfo.setWIDreceive_zip(ordership.getZip());//		payInfo.setWIDreceive_phone(ordership.getTel());//		payInfo.setWIDreceive_mobile(ordership.getPhone());		payInfo.setWIDsubject(order.getRemark());				payInfo.setLogistics_fee(Double.valueOf(order.getFee()));		payInfo.setLogistics_type(order.getExpressCode());				logger.error(payInfo.toString());		return payInfo;	}		/**	 * 查询我的订单列表信息	 */	@RequestMapping("selectList")	public String selectList(HttpServletRequest request, @ModelAttribute("e") Order e, ModelMap model) throws Exception 	{		int offset = 0;//分页偏移量		if (request.getParameter("pager.offset") != null) 		{			offset = Integer					.parseInt(request.getParameter("pager.offset"));		}		if (offset < 0)			offset = 0;		e.setOffset(offset);		PagerModel pager = getService().selectPageList(e);		if (pager == null) 		{			pager = new PagerModel();		}		// 计算总页数		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)				/ pager.getPageSize());		pager.setPagerUrl("myCarts");		model.addAttribute("pager", pager);		return "/account/orders";	}	/**	 * 删除我的订单信息	 */	@RequestMapping("deletes")	public String deletes(String[] ids, HttpServletRequest request, @ModelAttribute("e") Order e, ModelMap model) throws Exception 	{		getService().deletes(ids);		return selectList(request, e, model);	}		/**	 * 退订或取消指定的订单	 * @return	 * @throws Exception	 */	@RequestMapping("cancel")	public String cancel() throws Exception 	{		return "";	}		/**	 * 读取指定订单的信息	 * @return	 */	@RequestMapping("read")	public String read()	{		return "";	}		/**	 * 对指定的订单进行支付	 * @return	 *///	public String doPay(){//		if(1==1){//			throw new NullPointerException();//		}//		//		String orderID = getRequest().getParameter("orderID");//		e.clear();//		e.setId(orderID);//		e.setStatus(Order.order_status_init);//等待付款//		logger.error("orderid=" + orderID);//		orderService.update(e);//		return "doPay";//	}		/**     * 得到支付状态     *     * @return     */    @RequestMapping("getPayStatus")    public void getPayStatus(HttpServletResponse response) {        HttpSession session = RequestHolder.getRequest().getSession();        String orderCode = String.valueOf(session.getAttribute("orderCode"));        boolean orderPayStatus = orderService.payOrderStatus(orderCode);        response.setContentType("text/html;charset=UTF-8");        try {            if (orderPayStatus) {                response.getWriter().write("1");                return;            }            response.getWriter().write("0");        } catch (IOException e) {            logger.error(e.getMessage());        }    }		/**	 * 查看订单详情	 * @return	 */	@RequestMapping("{orderId}")	public String orderDetail(@PathVariable("orderId") String id, ModelMap model)	{		Account acc = getLoginAccount();		if (acc == null) 		{			return page_toLogin;		}		int productCount=productService.selectProductCount();		model.addAttribute("productCount", productCount);		logger.error("orderInfo...");		if(StringUtils.isBlank(id))		{			throw new NullPointerException("订单ID不能为空！");		}				//查询订单信息		Order order = new Order();		order.setId(id);		order.setAccount(acc.getAccountId());		List<Order> orders = orderService.selectOrderInfo(order);		Order e = orders.get(0);				if(orders==null || orders.size()==0)		{			throw new NullPointerException("根据订单ID查询不到订单信息！");		}		//商品规格		for (Order order2 : orders) 		{			if(!StringUtils.isBlank(order2.getSpecInfo()) && order2.getSpecInfo().indexOf(",")>0 ){				order2.setSpecInfo(order2.getSpecInfo().replace(",", "<br />"));				logger.debug("-------SpecInfo----------"+order2.getSpecInfo());			}		}		logger.error("orders.size="+orders.size());				logger.debug("-----------------order 转换前t_order.status = "+e.getStatus());		//失效订单状态处理		logger.debug("-----------------失效订单状态处理 InitStatus = "+e.getInitStatus()+"  PassStatus = "+e.getPassStatus()+"  ExpiredTime = "+e.getExpiredTime());		if(!StringUtils.isBlank(e.getInitStatus()) || !StringUtils.isBlank(e.getPassStatus()) || e.getExpiredTime() != null)		{			e.setStatus(com.soloyogame.anitoys.db.commond.Order.order_status_cancel);		}		logger.debug("-----------------order 转换后t_order.status = "+e.getStatus());				e.setOrders(orders);		//查询订单配送信息		Ordership ordership = new Ordership();		ordership.setOrderid(id);		ordership = ordershipService.selectOne(ordership);		if(ordership==null)		{			ordership = new Ordership();			//throw new NullPointerException("根据订单ID查询不到订单配送信息！");		}		e.setOrdership(ordership);		//查询订单物流信息		//e.setKuaid100Info(kuaidi100Helper.selectKuaidi100());		model.addAttribute("e", e);		//订单跟踪日志		Orderlog odlog = new Orderlog();		odlog.setOrderid(id);		model.addAttribute("logList",orderlogService.selectList(odlog));		//查询使用积分日志		AccountPointsLog pointsLog = new AccountPointsLog();		pointsLog.setUserId(e.getAccount());		pointsLog.setOrderId(e.getParentId());		List<AccountPointsLog> pointsLogList = orderService.selectOrderPoints(pointsLog);		model.addAttribute("pointsLogList",pointsLogList);		logger.debug("订单详情，订单使用积分详情：订单编号ParentId："+e.getParentId()+",有count="+pointsLogList.size()+"条订单积分使用详情");				//订单支付日志		Orderpay op = new Orderpay();		op.setOrderid(id);		List<Orderpay> payList = orderpayService.selectList(op);		model.addAttribute("payList",payList);				//根据订单ID得到订单消费余额的日志		AccountRankLog accountRankLog = new AccountRankLog();		accountRankLog.setUserId(acc.getId());		accountRankLog.setOrderId(id);		List<AccountRankLog> accountRankLogList = accountFinanceService.selectRankLogPageList(accountRankLog).getList();		model.addAttribute("accountRankLogList",accountRankLogList);		return "/account/orderDetail";	}		/**	 * 查看物流信息	 * @return	 */	@RequestMapping("orderhipInfo")	public String orderhipInfo()	{		logger.error("orderhipInfo...");		return "/account/orderhipInfo";	}	/**	 * 确认订单信息	 * @return	 */	@RequestMapping("confirmOrder")	public String confirmOrder(ModelMap model)	{		logger.error("confirmOrder..");		Account acc =getLoginAccount();		if (acc == null || StringUtils.isBlank(acc.getAccount())) 		{//			getSession().getAttribute(FrontContainer);			return page_toLoginRedirect;		}				//检查购买的商品是否超出可购买的库存数		CartInfo cartInfo = getMyCart();		if(cartInfo==null)		{			throw new NullPointerException("非法请求");		}		//		for(int i=0;i<cartInfo.getProductList().size();i++)//		{//			Product product = cartInfo.getProductList().get(i);//			ProductStockInfo stockInfo = SystemManager.getInstance().getProductStockMap().get(product.getId());//			if(stockInfo==null)//			{//				//商品已卖完或已下架，请联系站点管理员!//				throw new RuntimeException("商品已卖完或已下架，请联系站点管理员!");//			}//			else if(stockInfo.getStock() < product.getBuyCount())//			{//				//购买的商品数超出库存数//				throw new RuntimeException("商品已卖完或已下架，请联系站点管理员!");//			}//		}				//加载配送信息		Address add = new Address();		add.setAccountId(acc.getAccount());		List<Address> addressList = addressService.selectList(add);		cartInfo.setAddressList(addressList);		if(addressList!=null && addressList.size()>0)		{//			boolean exist = false;			for(int i=0;i<addressList.size();i++)			{				Address addItem = addressList.get(i);				if(StringUtils.isNotBlank(addItem.getIsdefault()) && addItem.getIsdefault().equals("y"))				{					cartInfo.setDefaultAddessID(addItem.getId());					break;				}			}		}		model.addAttribute("myCart", cartInfo);		model.addAttribute("expressList",loadExpress().values());		return "order/confirmOrder";	}		/**	 * 加载物流列表	 */	private Map<String, Express> loadExpress(){		List<Express> expressList = expressService.selectList(new Express());        Map<String, Express> expressMap = Maps.newHashMap();		if(expressList!=null && expressList.size()>0){			for(int i=0;i<expressList.size();i++){				Express item = expressList.get(i);				expressMap.put(item.getCode(), item);			}		}        return expressMap;	}		/**	 * 支付成功后，回调请求跳转到的页面	 * @return	 */	@RequestMapping(value="paySuccess", method = RequestMethod.POST)	@ResponseBody	public String paySuccess(ModelMap model)	{		logger.error("paySuccess...");		HttpSession session = RequestHolder.getRequest().getSession();		double payAccountAmount=Double.parseDouble(String.valueOf(session.getAttribute("payAccountAmount")));		java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00"); 		model.put("payAccountAmount", df.format(payAccountAmount));		String orderCode=String.valueOf(session.getAttribute("orderCode"));		boolean  orderPayStatus =orderService.payOrderStatus(orderCode);		if (orderPayStatus) 		{		    return "1";		}		else		{			return "0";		}	}		/**	 * 确认成功时跳转	 * @param model	 * @return	 */	@RequestMapping("paySuccessAgain")	public String paySuccessAgain(ModelMap model){		logger.error("paySuccess...");		HttpSession session = RequestHolder.getRequest().getSession();		if(session.getAttribute("payAccountAmount")!=null){			double payAccountAmount=Double.parseDouble(String.valueOf(session.getAttribute("payAccountAmount")));			java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00"); 			model.put("payAccountAmount", df.format(payAccountAmount));		}		return "order/paySuccess";	}			/**	 * 订单中心 - 确认收货	 * @return	 */	@RequestMapping("confirmReceipt")	public String confirmReceipt()	{		logger.info("confirmReceipt确认收货..");		Account acc =getLoginAccount();		if (acc == null || StringUtils.isBlank(acc.getAccount())) 		{			return page_toLoginRedirect;		}		String orderid = RequestHolder.getRequest().getParameter("orderid");		if(StringUtils.isBlank(orderid))		{			throw new NullPointerException("参数异常！");		}				/*		 * 用户可以对每个订单项对应的商品进行评价		 */		Orderlog orderlog = new Orderlog();		orderlog.setOrderid(orderid);		orderlog.setAccount(acc.getAccountId());		orderlog.setContent("【交易完成】");		orderlog.setAccountType(Orderlog.orderlog_accountType_w);		orderlog.setStatus(Orderlog.operate_status_c);//确认收货		orderService.updateOrderStatusByConfirm(orderlog);				//确认收货之后给客户添加积分		Order order = orderService.selectById(orderid);		double score = order.getScore();                //得到订单能够获得的积分		Map<String,Object> map=new HashMap<String,Object>();		map.put("type", 2);		map.put("id", acc.getId());		map.put("rank", score);		int a = accountFinanceService.updateAccountScore(map);		AccountPointsLog accLog = new AccountPointsLog();		if(a>0)		{			//账户积分日志记录			accLog.setId("0");			accLog.setUserId(acc.getId());			accLog.setRankCount(score);			accLog.setIsOrder(0);			pointsManageService.insert(accLog);		}		return "redirect:/account/orders";	}		/**	 * 取消订单	 * jiangyongzhi	 * @return	 */	@RequestMapping("delOrder")	public String delOrder(ModelMap model,RedirectAttributes flushAttrs) throws Exception 	{		logger.info("取消订单delOrder...");		Account acc = LoginUserHolder.getLoginAccount();		if (acc == null || StringUtils.isBlank(acc.getAccount()))		{			return page_toLoginRedirect;		}		String orderid = RequestHolder.getRequest().getParameter("orderid");		if(StringUtils.isBlank(orderid))		{			throw new NullPointerException("参数异常！");		}		Order param = new Order();		param.setAccount(acc.getAccountId());		param.setId(orderid);		List<Order> od = orderService.selectOrderInfo(param);		if(od != null && od.size()>0)		{			//用户可以对每个订单项对应的商品进行评价			Orderlog orderlog = new Orderlog();			orderlog.setOrderid(orderid);			orderlog.setAccount(acc.getAccountId());			orderlog.setContent("【取消订单】用户已取消订单");			orderlog.setAccountType(Orderlog.orderlog_accountType_w);			orderlog.setStatus(Orderlog.operate_status_q);//取消订单			orderService.updateOrderStatusByConfirm(orderlog);						//恢复商品库存			ProductStock ps = new ProductStock();			ps.setProductID(od.get(0).getProductID());			ps.setProductBuyNumber(od.get(0).getNumber());			orderService.addProductStock(ps);			//TODO 取消订单释放库存和购买数量			//TODO 发送取消订单邮件		}		else		{			throw new NullPointerException("订单不存在！");		}		flushAttrs.addFlashAttribute("orderCancel","订单已取消！");		return "redirect:/account/orders";	}	 	    /**	   	 * 查看指定订单的物流信息	   	 * 	   	 */		@RequestMapping("qryApiStoreInfo")		@ResponseBody		public List<Map<String,Object>> qryApiStoreInfo()		{			logger.info("qryApiStoreInfo查看物流");						String orderid = RequestHolder.getRequest().getParameter("orderid");			System.out.println("orderid:"+orderid);			if(StringUtils.isBlank(orderid))			{				throw new NullPointerException("参数异常！");			}						List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();			ApiStoreInfo apiStoreInfo=ApiStore.request("YUNDA", orderid);//orderid);			 ApiStoreItem result=apiStoreInfo.getResult();			 System.out.println("Msg:"+apiStoreInfo.getMsg());			 System.out.println("status:"+apiStoreInfo.getStatus());			 if(result!=null)			 {				 list=result.getList();				 System.out.println("issign:"+result.getIssign());				 for(Map<String,Object> map:list)				 {					 System.out.println("time"+map.get("time"));					 System.out.println("status"+map.get("status"));				 }			 }			return list;		}						public List<Map<String,Object>> qryApiStoreInfo(String orderid)		{			System.out.println("orderid:");			logger.info("qryApiStoreInfo查看物流");			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();			try 			{				 ApiStoreInfo apiStoreInfo=ApiStore.request("YUNDA", orderid);				 ApiStoreItem result=apiStoreInfo.getResult();				 System.out.println("Msg:"+apiStoreInfo.getMsg());				 System.out.println("status:"+apiStoreInfo.getStatus());				 if(result!=null)				 {					 list=result.getList();				 }							} 			catch (Exception e) 			{				logger.error("订单编号："+orderid+"， 当前查找不到物流信息："+e.getMessage(),e);			}			return list;		}				/**		 * 拦截404错误跳转页面		 * @param model		 * @return		 * @throws Exception		 */		@RequestMapping(value = "to404")		public String to404(ModelMap model) throws Exception 		{			logger.info("跳转404页面！");			return "404Ftl";		}				 /**	     * 快递费计算	     */	    @RequestMapping("getShiping")	    @ResponseBody	    public Object getShiping(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception 	    {	    	// 返回值	    	Map<String,Object> result = new HashMap<String, Object>();	        //获取前台传递的子订单号	        String orderCodeView = request.getParameter("sonorderCode");	        //前段传过来的子订单号	        String orderCode = request.getParameter("orderCode");	        	        logger.info("orderCodeView from ftl is " + orderCodeView);	        //获取前台传递的选中运送方式id	        String shippingId = request.getParameter("shippingId");	        //获取前台传递的选中地址id	        String addressId = request.getParameter("addressId");	        //运费价格	        double shipMoney = 0;	        //得到登录用户的信息	        Account account = LoginUserHolder.getLoginAccount();	        	        if (account == null || StringUtils.isBlank(account.getAccount())) 	        {	       	 	result.put("result", "needLogin");	            return JsonUtil.objectToJson(result);	        }	        Order sonOrderParam = new Order();	        sonOrderParam.setOrderCode(orderCode);	        Order sonOrder = orderService.selectFrontOne(sonOrderParam);//	        //获得选中快递方式信息			List<BusinessShipping> shipList = orderBusinessShippingService.queryOrderBusinessShipping(sonOrder.getBusinessId());	        BusinessShipping shipping = new BusinessShipping();	        for (int i = 0; i < shipList.size(); i++) 	        {	            BusinessShipping s = shipList.get(i);	            if (s.getShippingId().equals(shippingId)) 	            {	                shipping = s;	                break;	            }	        }	        logger.info("选中的快递为：" + shipping.getId());	        	        //获得选中运送地址	        Address address = addressService.selectById(addressId);	        logger.info("address.getProvince() = " + address.getProvince());	        //获得运费详情  用于计算	        BusinessShippingDetail businessShippingDetail = new BusinessShippingDetail();	        List<BusinessShippingDetail> shipdetailList = shipping.getBsdList();	        for (BusinessShippingDetail shippingDetail : shipdetailList) 	        {	            logger.info("shippingDetail.getProvinceId() = " + shippingDetail.getProvinceId());	            if (shippingDetail.getProvinceId().equals(address.getProvince())) 	            {	                businessShippingDetail = shippingDetail;	                break;	            }	        }			 /*			  * 如果运送方式不支持客户选中地址，则直接返回0运费			  */	        if (StringUtils.isNotBlank(businessShippingDetail.getId()))	        {	        		        	// 默认快递  运费为0	            if(shipping.getIsDefault()==1) 	            {	            	 result.put("result", shipMoney);	                 return JsonUtil.objectToJson(result);	            } 	            	            // 默认配送快递明细	            BusinessShippingDetail defaultShippingDetail = new BusinessShippingDetail();	            // 默认地址始终是第一个	            if(shipList.get(0).getIsDefault()==1) 	            {	            	BusinessShipping defaultShipping = shipList.get(0);	            	//获得默认快递运费详情  用于计算	                List<BusinessShippingDetail> defaultShippingdetailList = defaultShipping.getBsdList();	                for (BusinessShippingDetail shippingDetail : defaultShippingdetailList) 	                {	                    if (shippingDetail.getProvinceId().equals(address.getProvince())) 	                    {	                    	defaultShippingDetail = shippingDetail;	                    	 break;	                    }	                }	            }	            	            //商品所有重量	            double allWeight = 0;	            Orderdetail orderDetailParam = new Orderdetail();	            orderDetailParam.setOrderID(sonOrder.getId());	            List<Orderdetail> OrderdetailList = orderdetailService.selectList(orderDetailParam);	            for (Orderdetail orderdetail : OrderdetailList) 	            {	                double productWeight = 0;	                if (orderdetail.getProductWeight() != null && orderdetail.getProductWeight() != "") 	                {	                	productWeight = Double.parseDouble(orderdetail.getProductWeight()); //单个商品重量	                }	                double pCnt = orderdetail.getNumber();  //商品数量	                allWeight = productWeight * pCnt;	            }	            	            // 默认快递 运费	            double defaultFee = 0;	            if(StringUtils.isNotBlank(defaultShippingDetail.getId())) 	            {	            	 //商品重量向上取整	                double defaultFirstHeavy = Double.parseDouble(businessShippingDetail.getFirstHeavy());//商品首重	                if (allWeight <= defaultFirstHeavy) 	                {	                    //商品重量小于等于首重。价格取首重价格	                	defaultFee = defaultShippingDetail.getFristPrice();	                } 	                else 	                {	                    double weight = allWeight - defaultFirstHeavy;	                    double setpHeavy = Double.parseDouble(defaultShippingDetail.getStepHeavy());	                    double hmg = weight / setpHeavy; //快递规格	                    int cnt = (int) Math.ceil(hmg);	                    defaultFee = defaultShippingDetail.getFristPrice();	                    defaultFee = defaultFee + (cnt * defaultShippingDetail.getStepPrice());	                }	                	            }	            // 当前选中快递 运费	            double currentFee = 0;	            //商品重量向上取整	            double firstHeavy = Double.parseDouble(businessShippingDetail.getFirstHeavy());//商品首重	            if (allWeight <= firstHeavy) 	            {	                //商品重量小于等于首重。价格取首重价格	            	currentFee = businessShippingDetail.getFristPrice();	            }	            else 	            {	                double weight = allWeight - firstHeavy;	                if(businessShippingDetail.getStepHeavy()!=null) 	                {	                	double setpHeavy = Double.parseDouble(businessShippingDetail.getStepHeavy());	                	double hmg = weight / setpHeavy; //快递规格	                    int cnt = (int) Math.ceil(hmg);	                    currentFee = businessShippingDetail.getFristPrice();	                    currentFee = currentFee + (cnt * businessShippingDetail.getStepPrice());	                } 	            }	            	            shipMoney = currentFee - defaultFee;	            if(shipMoney<0) 	            {	            	shipMoney = 0;	            }	            result.put("result", shipMoney);	            return JsonUtil.objectToJson(result);	        }	        else 	        {	        	result.put("result", "noMatch");	            return JsonUtil.objectToJson(result);	        }	    }	    	    /**	     * 商家优惠券使用	     */	    @RequestMapping("getCoupon")	    @ResponseBody	    public Object getCoupon(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception 	    {	    	 	    	 // 获取当前登录用户信息	    	 Account account = getLoginAccount();	    	 Map<String,Object> result = new HashMap<String, Object>();	         if (account == null || StringUtils.isBlank(account.getAccount())) 	         {	        	 result.put("result", "needLogin");	             return JsonUtil.objectToJson(result);	         }	         //	获取前台传递的选中优惠券id	         String couponId = request.getParameter("couponId");	         //	获取前台传递的子订单codeView	         String sonorderCode = request.getParameter("sonorderCode");	         // 前段传过来的子订单号		     String orderCode = request.getParameter("orderCode");		     		     //释放此订单以前绑定的优惠券(结束数据库中我的优惠券绑定的订单ID)	         removeCouponBinding(sonorderCode,account.getId());	         	         AccountCoupon accountCoupon = new AccountCoupon();	         accountCoupon.setId(couponId);	         accountCoupon.setUserId(account.getId());	         AccountCoupon coupon = accountCouponService.selectAccountCouponInfo(accountCoupon);	         //如果优惠券被绑定订单了，则检查顶大是否超过失效时间,超过则解绑	         if (coupon!=null && StringUtils.isNotBlank(coupon.getOrderId())) 	         {	        	//根据订单号查询父订单是否过期	             String oldparentOrderkey=account.getId()+ManageContainer.PARENT_ORDER+coupon.getOrderId();	             Order oldparentOrder = JSON.parseObject(redisClient.get(oldparentOrderkey), Order.class);	             if(oldparentOrder==null){	            	 removeCouponBinding(coupon.getOrderId(),account.getId());	             }	         }	         	         if (coupon!=null && (coupon.getStatus() == 2 || StringUtils.isNotBlank(coupon.getOrderId()))) 	         {	        	 result.put("result", "couponUsed");	             return JsonUtil.objectToJson(result);	         }	         	         //如果优惠券没有被使用则绑定优惠券订单code	         if(coupon!=null)	         {	        	 coupon.setCouponId(couponId);	        	 bindingCoupon(coupon,sonorderCode);	         }	        	         Order sonOrderParam = new Order();		     sonOrderParam.setOrderCode(orderCode);		     Order sonOrder = orderService.selectFrontOne(sonOrderParam);	         double sonAmount = Double.valueOf(sonOrder.getBalancePrice());	         if(coupon!=null)	         {	        	 double couponValue = Double.valueOf(coupon.getCouponValue());		         // 1 :抵价券    2：折扣券		         if(coupon.getCouponType()==2) 		         {		        	 sonAmount = sonAmount * (couponValue/10);		         } 		         else 		         {		        	 sonAmount = sonAmount - couponValue;		        	 if(sonAmount<0) 		        	 {		        		 sonAmount = 0;		        	 }		         }	         }	         result.put("result", sonAmount);	    	 return JsonUtil.objectToJson(result);	    }	    	    /**	     * 解绑优惠券	     */	    private void removeCouponBinding(String orderId,String accountId)	    {	    	 //解绑此订单以前绑定的优惠券（数据库）	        AccountCoupon accountCouponold = new AccountCoupon();	        accountCouponold.setUserId(accountId);	        accountCouponold.setOrderId(orderId);	        AccountCoupon couponold = accountCouponService.selectAccountCouponInfo(accountCouponold);	        if(couponold!=null && StringUtils.isNotBlank(couponold.getOrderId()))	        {	       	 couponold.setOrderId(null);	       	 accountCouponService.update(couponold);	        }	        //缓存释放优惠券	        String key=orderId+ManageContainer.COUPON_BINDING;	        String s = redisClient.get(key);	        redisClient.del(key);	    }	    	    /**	     * 绑定优惠券到订单	     */	    public void bindingCoupon(AccountCoupon accountCoupon,String orderId)	    {	    	//设置优惠券绑定的有效时间	        Properties  properties = PropertiesUtil.findCommonPro("config.properties");	    	 //数据库优惠券绑定订单ID	        accountCoupon.setOrderId(orderId);	        accountCouponService.update(accountCoupon);	        //缓存锁定优惠券	        String key=orderId+ManageContainer.COUPON_BINDING;	        int expiredTime = Integer.valueOf(properties.getProperty("binding_expiredTime"));	        redisClient.set(key,accountCoupon.getCouponId(), expiredTime);	        String S = redisClient.get(key);	    }	    	    /**	     * 平台抵扣券使用	     */	    @RequestMapping("getVoucher")	    @ResponseBody	    public Object getVoucher(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception 	    {	    	 // 获取当前登录用户信息	    	 Account account = getLoginAccount();	    	 Map<String,Object> result = new HashMap<String, Object>();	         if (account == null || StringUtils.isBlank(account.getAccount())) 	         {	        	 result.put("result", "needLogin");	             return JsonUtil.objectToJson(result);	         }	         //	获取前台传递的选中抵扣券id	         String deductibleId = request.getParameter("deductibleId");	         //获取前台传递的母订单编号	         String orderId = request.getParameter("orderId");	         	         //解绑此订单以前绑定的平台抵扣券	         removeBindingVoucher(account.getId(),orderId);	         	         AccountDeductibleVoucher accountDeductibleVoucher = new AccountDeductibleVoucher();	         accountDeductibleVoucher.setId(deductibleId);	         accountDeductibleVoucher.setUserId(account.getId());	         AccountDeductibleVoucher deductibleVoucher = accountDeductibleVoucherService.selectOne(accountDeductibleVoucher);	         	        //如果优惠券被绑定订单了，则检查订单是否超过失效时间,超过则解绑	         if (deductibleVoucher!=null && StringUtils.isNotBlank(deductibleVoucher.getOrderId())) 	         {	        	 //根据订单号查询父订单是否过期	             String oldparentOrderkey=account.getId()+ManageContainer.PARENT_ORDER+deductibleVoucher.getOrderId();	             Order oldparentOrder = JSON.parseObject(redisClient.get(oldparentOrderkey), Order.class);	             if(oldparentOrder==null)	             {	            	 removeBindingVoucher(account.getId(),deductibleVoucher.getOrderId());	             }	         }	         	         if (deductibleVoucher!=null && (deductibleVoucher.getStatus() == 2 || StringUtils.isNotBlank(deductibleVoucher.getOrderId()))) 	         {	        	 result.put("result", "couponUsed");	             return JsonUtil.objectToJson(result);	         }	         	         //如果抵扣券没有被使用则绑定抵扣券订单code	         if(deductibleVoucher!=null)	         {	        	 deductibleVoucher.setDeductibleId(deductibleId);	        	 bindingVoucher(deductibleVoucher,orderId);	        	 result.put("result", deductibleVoucher.getDeductibleValue());	         }	         else	         {	        	 result.put("result", "0.0");	         }	    	 return JsonUtil.objectToJson(result);	    }	    	    /**	     * 绑定抵扣券到订单	     */	    public void bindingVoucher(AccountDeductibleVoucher deductibleVoucher,String orderId)	    {	    	 //设置优惠券绑定的有效时间	         Properties  properties = PropertiesUtil.findCommonPro("config.properties");	    	 deductibleVoucher.setOrderId(orderId);	    	 accountDeductibleVoucherService.update(deductibleVoucher);	    	 String key=orderId+ManageContainer.VOUCHER_BINGING;	         int expiredTime = Integer.valueOf(properties.getProperty("binding_expiredTime"));	         redisClient.set(key, deductibleVoucher.getDeductibleId(), expiredTime);	    }	    	    /**	     * 解绑订单的平台抵扣券	     */	    public void removeBindingVoucher(String accountId,String orderId)	    {	    	//解绑此订单以前绑定的平台抵扣券	        AccountDeductibleVoucher accountDeductibleVoucherOld = new AccountDeductibleVoucher();	        accountDeductibleVoucherOld.setUserId(accountId);	        accountDeductibleVoucherOld.setOrderId(orderId);	        AccountDeductibleVoucher deductibleVoucherOld = accountDeductibleVoucherService.selectOne(accountDeductibleVoucherOld);	        if(deductibleVoucherOld!=null && StringUtils.isNotBlank(deductibleVoucherOld.getOrderId()))	        {	       	 deductibleVoucherOld.setOrderId(null);	       	 accountDeductibleVoucherService.update(deductibleVoucherOld);	        }	        	       //缓存释放抵扣券	        String key=orderId+ManageContainer.VOUCHER_BINGING;	        redisClient.del(key);	    }	    	    /**	     * 绑定积分使用	     */	    @RequestMapping("bindingAccountScore")	    @ResponseBody	    public Object bindingAccountScore(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception 	    {	    	 // 获取当前登录用户信息	    	 Account account = getLoginAccount();	    	 Map<String,Object> result = new HashMap<String, Object>();	         if (account == null || StringUtils.isBlank(account.getAccount())) 	         {	        	 result.put("result", "needLogin");	             return JsonUtil.objectToJson(result);	         }	         	         //	获取前台传递的用户使用的积分	         String accountScore = request.getParameter("accountScore");	         //获取前台传递的母订单编号	         String orderId = request.getParameter("orderId");	         	         //设置积分绑定的有效时间	         Properties  properties = PropertiesUtil.findCommonPro("config.properties");	         String keyaccountRank=account.getId()+ManageContainer.ORDER_RANK;	         String keyorderRank=orderId+ManageContainer.ORDER_RANK;	         int expiredTime = Integer.valueOf(properties.getProperty("binding_expiredTime"));	         	         //根据用户id获取用户积分信息	         int rank = 0;	         int accountBindScore=0;  //这个用户总共锁定的积分	         int orderBindScore=0;    //当前这个订单绑定的积分	         int oldOrderBingScore=0; //这个订单之前绑定的积分	         	         //得到这个订单之前绑定的积分	         if(redisClient.get(keyorderRank)!=null){	        	 oldOrderBingScore = Integer.valueOf(redisClient.get(keyorderRank).toString());     //订单锁定的积分	         }	         	         //如果这个用户之前还有绑定的积分	         if(redisClient.get(keyaccountRank)!=null){	        	 accountBindScore = Integer.valueOf(redisClient.get(keyaccountRank).toString())+Integer.valueOf(accountScore)-oldOrderBingScore;	         }	         else{	        	 accountBindScore =  Integer.valueOf(accountScore);	         }	         	         //得到用户真实的积分	         AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());	         if (accountFinance != null) 	         {	             rank = accountFinance.getRank();	         }	         	         //设置用户绑定的积分和这个订单绑定的积分	         redisClient.set(keyaccountRank,String.valueOf(accountBindScore), expiredTime);	    	 redisClient.set(keyorderRank,accountScore, expiredTime);       	         //将用户积分信息传递前台	         result.put("result", Integer.valueOf(rank)-accountBindScore);	    	 return JsonUtil.objectToJson(result);	    }	    	    /**	     * 解绑订单的积分锁定	     */	    public void removeBindingScore(String accountId,String orderId)	    {	    	//缓存释放积分	        String key=accountId+ManageContainer.ORDER_RANK;	        redisClient.del(key);	    }	    	    protected CartInfo getMyCart()	    {	    	//return (CartInfo) RequestHolder.getSession().getAttribute(FrontContainer.myCart);	    	Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息	    	CartInfo cartInfo = null;	    	if(account==null)			{				cartInfo = (CartInfo) redisCacheProvider.get("myCart");			}			else			{				cartInfo = (CartInfo) redisCacheProvider.get("user_"+account.getId()+"Cart");			}	    	return cartInfo;	    }	    	    /**	     * check配送地址数量	     *	     * @return	     * @throws Exception	     */	    @RequestMapping("checkMysite")	    @ResponseBody	    public Object checkMysite(ModelMap model) 	    {	        Map<String, String> result = new HashMap<String, String>();	        Account acc = LoginUserHolder.getLoginAccount();	        Address address = new Address();	        address.setAccountId(acc.getId());	        int count = addressService.selectCountByAccountId(address);	        if (count > addressCount) {	            result.put("result", "error");	        } else {	            result.put("result", "ok");	        }	        return JsonUtil.objectToJson(result);	    }	    	    /**	     * 保存配送地址	     * @return	     * @throws Exception	     */	    @RequestMapping("saveMysite")	    public String saveMysite(ModelMap model, Address address) throws Exception 	    {	    	url = RequestHolder.getRequest().getHeader("Referer");	        Account acc = LoginUserHolder.getLoginAccount();	        if (acc == null || StringUtils.isBlank(acc.getAccount())) {	        	return page_toLogin;	        }	        int productCount = productService.selectProductCount();	        model.addAttribute("productCount", productCount);	        address.setProvinceId(address.getProvince());	        //需要将省市区的代号换成中文，插入到pcadetail字段里面去，显示的时候方便。	        StringBuilder pcadetail = new StringBuilder();	        Map<String, Area> areaMap = loadArea();	        Area sheng = areaMap.get(address.getProvince());//省	        pcadetail.append(sheng.getName());	        for (int i = 0; i < sheng.getChildren().size(); i++) {	            Area shi = sheng.getChildren().get(i);//市	            if (shi.getCode().equals(address.getCity())) {	                pcadetail.append(" ").append(shi.getName());	                for (int j = 0; j < shi.getChildren().size(); j++) {	                    Area qu = shi.getChildren().get(j);//区	                    if (qu.getCode().equals(address.getArea())) {	                        pcadetail.append(" ").append(qu.getName());	                        break;	                    }	                }	                break;	            }	        }	        address.setPcadetail(pcadetail.toString());	        address.setAccountId(acc.getId());	        if (address.getIsdefault() == null || !address.getIsdefault().equals("y"))	            address.setIsdefault("n");	        if (address.getIsdefault() != null && address.getIsdefault().equals("y")) {	            address.setIsdefault("y");	            //修改其他地址不为默认;	            Address updefault = new Address();	            updefault.setAccountId(acc.getId());	            addressService.upDefault(updefault);	        }	        if (StringUtils.isBlank(address.getId())) {	            addressService.insert(address);	            return "redirect:"+url;	        } else {	            addressService.update(address);	            return "redirect:"+url;	        }	    }}